<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
 * 定时任务
*/

class Cron extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        // $this->admin_init();
        // 加载类库
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        $this->load->model('dataModel');
    }

    public function index() {
        // 自动更新年级
        $this->__auto_upgrade_grade();
        exit(json('更新数据成功', true));
    }

    // 定时发布动态
    public function news() {
        $teachParams['isDelete'] = 0;
        $teachParams['allUserType'] = 1;
        $teacherList = $this->schoolModel->get_teacher_list($teachParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取待发送动态
        // 过滤软删除
        $data['isDelete'] = 0;
        $data['isCron'] = 1;
        $newsList = $this->contentModel->get_news_list($data);
        $count = 0;
        if($newsList) {
            foreach($newsList as $news) {
                $crontime = $news['crontime'];
                if($crontime <= date('Y-m-d H:i:s')) {
                    // 发布动态
                    $this->db->update(ContentModel::$newsTable, array(
                        'is_cron' => 0,
                        'updatetime' => date('Y-m-d H:i:s'),
                    ), array(
                        'id' => $news['id']
                    ));
                    // 推送消息到客户端
                    $this->load->library('socket');
                    $this->socket->send_news_msg($news['school_id'], $news['class_id'], $news['id']);

                    // 发布班级，如大于3个，截取前3个班级
                    $classNameStr = $this->_get_class_name_str($news['class_id']);
                    $arr = explode('、', $classNameStr);
                    if(count($arr) > 3) {
                        $newArr = array_slice($arr, 0, 3);
                        $classNameStr = implode('、', $newArr) . '...';
                    }
                    if(isset($teacherList[$news['user_id']])) {
                        if($teacherList[$news['user_id']]['realname']) {
                            $realname = $teacherList[$news['user_id']]['realname'];
                        } else {
                            $realname = $teacherList[$news['user_id']]['username'];
                        }
                    } else {
                        $realname = '';
                    }

                    $data = array(
                        'keyword1' => array(
                            'value' => $classNameStr
                        ),
                        'keyword2' => array(
                            'value' => $realname
                        ),
                        'keyword3' => array(
                            'value' => date('Y-m-d H:i:s')
                        ),
                        'keyword4' =>  array(
                            'value' => '类型：班级动态'
                        )
                    );
                    $url =wx_url('classes/news_detail/') . $news['id'];
                    // // 发送模板消息
                    // $this->load->library('wxtemplate');
                    // $this->wxtemplate->send_template_msg($news['class_id'], WX_TEMPLATE_NOTIFY, $data, $url, 1);

                    // 获取学生列表
                    $stuParams['isDelete'] = 0;
                    $stuParams['schoolId'] = $news['school_id'];
                    $stuParams['classSet'] = $news['class_id'];
                    $students = $this->schoolModel->get_student_list($stuParams);
                    if($students) {
                        $this->load->model('wxUserModel');
                        // 截取成100个
                        $arr = array_chunk($students, 100);
                        foreach($arr as $studentArr) {
                            $processDataArr = array();
                            foreach($studentArr as $student) {
                                array_push($processDataArr, array(
                                    'student_id' => $student['id'],
                                    'data' => $data 
                                ));
                            }
                            $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                                'template_id' => WX_TEMPLATE_NOTIFY,
                                'type' => 'student',
                                'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                                'url' => $url
                            ));
                        }
                    }

                    $count++;
                }
            }
        }
        exit(json('发布了' . $count . '条动态', true));
    }

    // 定时发送模板消息通知过期家长账号
    public function notify_expire() {
        $this->load->model('wxUserModel');
        // 获取年级列表
        $schoolParams['isDelete'] = 0;
        $schoolList = $this->schoolModel->get_school_list($schoolParams);
        foreach($schoolList as $school) {
            $dateBefore = date('Y-m-d', strtotime('+7 days'));
            if($school['expire_date'] && $school['expire_date'] <= $dateBefore && $school['notify_expire_time']) {
                // 获取过期学生
                $stuParams['schoolId'] = $school['id'];
                // $stuParams['isExpired'] = 1;
                // 7天内过期的也发送消息
                $stuParams['expiredSoon'] = 1;
                $stuParams['isDelete'] = 0;
                $studentList = $this->schoolModel->get_student_list($stuParams);
                // 学校通知过期账号时间
                $notifyExpireTime = $school['notify_expire_time'];
                // 截取时
                $hour = explode(":", $notifyExpireTime)[0];
                // var_export($hour);var_export(date('H'));exit;
                if($hour != date('H')) {
                    // 时间没到，跳过
                    continue;
                }
                $data = array(
                    'first' => array(
                        'value' => ''
                    ),
                    'keynote1' => array(
                        'value' => $school['expire_date']
                    ),
                    'keynote2' => array(
                        'value' => '账号到期后，未续费的账号将无法收到学校动态、作业以及考勤等重要内容。'
                    ),
                    'remark' =>  array(
                        'value' => '请点击“详情”续费激活账号。'
                    )
                );
                $url = wx_url('home/index');
                // 截取成100个
                $arr = array_chunk($studentList, 100);
                foreach($arr as $studentArr) {
                    $processDataArr = array();
                    foreach($studentArr as $student) {
                        $data['first'] = array(
                            'value' => '您好，' . $student['realname'] . '账号已过期，请及时激活。'
                        );
                        array_push($processDataArr, array(
                            'student_id' => $student['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_EXPIRE,
                        'type' => 'student',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url,
                        'include_expired' => 1
                    ));
                }
            }
        }
        exit(json('执行成功', true));
    }

    // 自动更新年级
    private function __auto_upgrade_grade() {
        // 获取所有年级列表
        $allGradeParams['isDelete'] = 0;
        $allGradeParams['hasDefaultGradeId'] = 1;
        $allGradeList = $this->classesModel->get_grade_list($allGradeParams);
        // 将年级id和default_grade_id作为键值
        $allGradeList = array_value_to_key($allGradeList, 'school_id,default_grade_id');
        // echo '<pre>';var_export($allGradeList);exit;

        // 获取今天可更新年级列表
        $gradeParams['isDelete'] = 0;
        $gradeParams['hasDefaultGradeId'] = 1;
        $gradeParams['autoUpgradeDate'] = date('Y-m-d');
        // 排除毕业年级
        $gradeParams['excludeGraduated'] = 1;
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取默认年级列表
        $defaultParams['is_delete'] = 0;
        $defaultGradeList = $this->classesModel->get_default_grade_list($defaultParams);
        // 将id作为键值
        $defaultGradeList = array_value_to_key($defaultGradeList, 'id');
        // echo '<pre>';var_export($gradeList);exit;
        if($gradeList) {
            // 毕业年级id数组
            $graduatedGradeIdArr = array(); 
            foreach($gradeList as $grade) {
                $defaultGradeId = $grade['default_grade_id'];
                $defaultGrade = $defaultGradeList[$defaultGradeId];
                if($defaultGrade) {
                    $nextId = $defaultGrade['next_grade_id'];
                    $nextDefaultGradeInfo = $defaultGradeList[$nextId];
                    if($nextDefaultGradeInfo['next_grade_id'] == 0) {
                        // 毕业年级设置年级别名为‘毕业年级’,避免影响导入年级时，根据年级名称筛选
                        $this->db->update(ClassesModel::$gradeTable, array(
                            'updatetime' => date('Y-m-d H:i'),
                            'default_grade_id' => $nextId,
                            'grade_name' => $nextDefaultGradeInfo['name']
                        ), "id={$grade['id']}");
                        array_push($graduatedGradeIdArr, $grade['id']);
                    } else {
                        // 获取下一年级基本信息
                        $gradeName = $nextDefaultGradeInfo['name'];
                        if(isset($allGradeList[$grade['school_id'] . $nextId])) {
                            $nextGradeInfo = $allGradeList[$grade['school_id'] . $nextId];
                            $gradeName = $nextGradeInfo['grade_name'];
                        }
                        // 升级
                        $this->db->update(ClassesModel::$gradeTable, array(
                            'updatetime' => date('Y-m-d H:i:s'),
                            'default_grade_id' => $nextId,
                            'grade_name' => $gradeName
                        ), "id={$grade['id']}");
                    }
                }
            }
            // 设置is_graduated=1
            if($graduatedGradeIdArr) {
                $gradeIdSet = implode(',', $graduatedGradeIdArr);
                $this->db->where_in("id", $graduatedGradeIdArr);
                $this->db->update(ClassesModel::$gradeTable, array('is_graduated' => 1));
                // 设置班级表
                $classParams['isDelete'] = 0;
                $classParams['gradeIdSet'] = $gradeIdSet;
                $classList = $this->classesModel->get_class_list($classParams);
                if($classList) {
                    $classIdArr = array();
                    foreach($classList as $class) {
                        array_push($classIdArr, $class['id']);

                        // 删除毕业班的课程course
                        $this->db->update(DataModel::$scheduleLessonTable, array('is_delete' => 1), array(
                            'class_id' => $class['id'],
                            'is_delete' => 0
                        ));
                    }
                    $classIdSet = implode(',', $classIdArr);
                    $this->db->where_in("id", $classIdArr);
                    $this->db->update(ClassesModel::$classTable, array('is_graduated' => 1));
                    // 设置学生表
                    $params['isDelete'] = 0;
                    $params['field'] = "id";
                    $params['classSet'] = $classIdSet;
                    $studentList = $this->schoolModel->get_student_list($params);
                    if($studentList) {
                        $studentIdArr = array();
                        foreach($studentList as $student) {
                            array_push($studentIdArr, $student['id']);
                        }
                        $this->db->where_in("id", $studentIdArr);
                        $this->db->update(SchoolModel::$schoolStudentTable, array('is_graduated' => 1));
                    }
                }

                foreach($graduatedGradeIdArr as $graduatedGradeId) {
                    // 插入闸机任务
                    $gradeInfo = $this->classesModel->get_grade_info($graduatedGradeId);
                    $gateParams['schoolId'] = $gradeInfo['school_id'];
                    $gateParams['campusId'] = $gradeInfo['campus_id'];
                    // 过滤软删除
                    $gateParams['isDelete'] = 0;
                    $gateList = $this->schoolModel->get_gate_list($gateParams);
                    // 获取年级下的班级
                    $classArr = $this->classesModel->get_class_list_by_grade($graduatedGradeId);

                    if($gateList && $classArr) {
                        $classIdArr = array();
                        foreach($classArr as $class) {
                            array_push($classIdArr, $class['id']);
                        }
                        $classIdSet = implode(',', $classIdArr);
                        $insertTaskBatch = array();
                        // 添加闸机任务，遍历全校区有录入人脸的学生
                        $studentParams['schoolId'] = $gradeInfo['school_id'];
                        $studentParams['campusId'] = $gradeInfo['campus_id'];
                        $studentParams['classSet'] = $classIdSet;
                        $studentParams['isDelete'] = 0;
                        $studentParams['hasFaceImage'] = 1;
                        $studentParams['includeGraduated'] = 1;
                        $studentList = $this->schoolModel->get_student_list($studentParams);
                        foreach($gateList as $gate) {
                            $insertTaskBatch = array();
                            foreach($studentList as $student) {
                                array_push($insertTaskBatch, array(
                                    'school_id' => $gradeInfo['school_id'],
                                    'campus_id' => $gradeInfo['campus_id'],
                                    'gate_id' => $gate['id'],
                                    'device_sn' => $gate['device_sn'],
                                    'user_id' => $student['id'],
                                    'user_name' => $student['realname'],
                                    'user_face_image' => $student['face_image'],
                                    'user_type' => GATE_USER_TYPE_STUDENT,
                                    'task_type' => GATE_TASK_TYPE_DELETE,
                                    'task_state' => GATE_TASK_STATE_NEW,
                                    'createtime' => date('Y-m-d H:i:s'),
                                    'updatetime' => date('Y-m-d H:i:s')
                                ));
                            }
                            // echo '<pre>';var_export($insertTaskBatch);exit;
                            if($insertTaskBatch) {
                                $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
                            }
                        }
                    }

                    // 插入一体机任务
                    $this->load->model('aioModel');
                    $aioParams['schoolId'] = $gradeInfo['school_id'];
                    $aioParams['campusId'] = $gradeInfo['campus_id'];
                    // 过滤软删除
                    $aioParams['isDelete'] = 0;
                    $aioList = $this->aioModel->get_aio_list($aioParams);
                    if($aioList && $classArr) {
                        $classIdArr = array();
                        foreach($classArr as $class) {
                            array_push($classIdArr, $class['id']);
                        }
                        $classIdSet = implode(',', $classIdArr);
                        $insertTaskBatch = array();
                        // 添加一体机任务，遍历全校区有录入人脸的学生
                        $studentParams['schoolId'] = $gradeInfo['school_id'];
                        $studentParams['campusId'] = $gradeInfo['campus_id'];
                        $studentParams['classSet'] = $classIdSet;
                        $studentParams['isDelete'] = 0;
                        $studentParams['hasFaceImage'] = 1;
                        $studentParams['includeGraduated'] = 1;
                        $studentList = $this->schoolModel->get_student_list($studentParams);
                        foreach($aioList as $aio) {
                            foreach($studentList as $student) {
                                array_push($insertTaskBatch, array(
                                    'school_id' => $student['school_id'],
                                    'campus_id' => $student['campus_id'],
                                    'aio_id' => $aio['id'],
                                    'facesluice_id' => $aio['facesluice_id'],
                                    'user_id' => $student['id'],
                                    'user_name' => $student['realname'],
                                    'user_face_image' => $student['face_image'],
                                    'user_type' => AIO_USER_TYPE_STUDENT,
                                    'task_type' => AIO_TASK_TYPE_DELETE,
                                    'task_state' => AIO_TASK_STATE_NEW,
                                    'createtime' => date('Y-m-d H:i:s'),
                                    'updatetime' => date('Y-m-d H:i:s')
                                ));
                            }
                        }
                        if($insertTaskBatch) {
                            $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
                        }
                    }
                }

            }
        }
    }

    // 清空考勤临时表
    public function truncate_student_sign_temp() {
        $hour = (int) date('H');
        if($hour == 0 || $hour == 23) {
            $this->db->truncate(ClassesModel::$signTempTable);
            exit(json('清空考勤临时表成功', true));
        } else {
            exit(json('未到执行时间', true));
        }
    }

    // 设置所有班牌离线
    public function set_all_brand_offline() {
        $hour = (int) date('H');
        if($hour == 0 || $hour == 23) {
            $this->db->update(ClassesModel::$brandTable, array(
                'is_online' => 0,
                'offline_time' => date('Y-m-d H:i:s')
            ), array(
                'is_online' => 1
            ));
            exit(json('设置所有班牌离线成功', true));
        } else {
            exit(json('未到执行时间', true));
        }
    }

}